package com.oocl.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.oocl.log4j.Log4j;
import com.oocl.util.JsonUtil;
import com.oocl.vo.ItemVO;
import com.oocl.vo.MerchandiseVO;

/**
 * Servlet implementation class PlusOneItemToCartServlet
 */
public class PlusOneItemToCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		String newItemJSON = java.net.URLDecoder.decode(request.getParameter("newItemJSON"),"utf-8");
		Log4j.getLogger().info("收到的新条目信息为{}", newItemJSON);
		ItemVO itemVO = (ItemVO) JsonUtil.parserToDTO(newItemJSON, ItemVO.class);
		
		HttpSession session = request.getSession();
		Map<String, MerchandiseVO> shoppingCart = (HashMap<String, MerchandiseVO>) session.getAttribute("shoppingCart");
		MerchandiseVO merchandiseVO = shoppingCart.get(itemVO.getMerchandiseId());
		merchandiseVO.setCount(itemVO.getCount()+1);
		merchandiseVO.setTotalMoney(merchandiseVO.getCount() * merchandiseVO.getPrice());
		shoppingCart.put(itemVO.getMerchandiseId(), merchandiseVO);
		session.setAttribute("shoppingCart", shoppingCart);
		
		response.getWriter().write(JsonUtil.parserMerchandiseVOToString((Map<String, MerchandiseVO>) session.getAttribute("shoppingCart")));
		//接下来是从session load data
	}

}
